package ml.kupin.order.controller;

import ml.kupin.cart.service.CartService;
import ml.kupin.common.constant.KuPinConstant;
import ml.kupin.common.utils.KuPinResult;
import ml.kupin.order.pojo.DetailedOrder;
import ml.kupin.order.service.OrderService;
import ml.kupin.pojo.TbItem;
import ml.kupin.pojo.TbOrder;
import ml.kupin.pojo.TbUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * 订单管理Controller
 * <p>
 * Created by 小柯(Allen Kerr) on 17.5.8 18:48.
 */
@Controller
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private CartService cartService;

    @Autowired
    private OrderService orderService;

    @Value("${cart_web_url}")
    private String cart_web_url;

    private Logger logger = LoggerFactory.getLogger(OrderController.class);

    /**
     * 从购物车点击取结算，跳转到确认订单页面
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/cart2order")
    public String cart2order(HttpServletRequest request, Model model) {
        //从request域中取user
        TbUser user = (TbUser) request.getAttribute("user");

        //根据用户id取收货地址列表 ——> 使用静态数据
        //取支付方式列表 ——> 静态数据

        //根据用户id取购物车列表
        List<TbItem> cartItemList = cartService.getCartItemList(user.getId());

        //如果购物车为空，跳转到购物车页面
        if (cartItemList == null || cartItemList.size() == 0) {
//            System.out.println("购物车为空！");
            return "redirect:" + cart_web_url + "/cart.html";
        }

        //把购物车列表传递给jsp
        model.addAttribute("cartList", cartItemList);
        //返回逻辑视图
        return "cart2order";
    }

    /**
     * 点击提交订单，跳转到订单详情页面
     *
     * @return
     */
    @RequestMapping(value = "/submitOrder", method = RequestMethod.POST)
    public String submitOrder(DetailedOrder detailedOrder, HttpServletRequest request) {
        //取user
        TbUser user = (TbUser) request.getAttribute("user");
        //将userId、buyerNick(即username)封装进detailedOrder
        detailedOrder.setUserId(user.getId());
        detailedOrder.setBuyerNick(user.getUsername());
        //调用服务层处理detailedOrder
        KuPinResult kuPinResult = null;
        try {
            kuPinResult = orderService.createOrder(detailedOrder);
        } catch (Exception e) {
            e.printStackTrace();
            //捕获异常，订单生成失败！
            logger.error("订单生成失败！", e);
            return "redirect:" + cart_web_url + "/cart.html";
        }
        //如果订单生成成功，要删除购物车
        if (kuPinResult.getStatus() == KuPinConstant.KuPinResult_status_success) {
            logger.info("用户 " + user.getId() + " 下单成功，订单编号：" + kuPinResult.getData());
            //清空购物车
            cartService.clearCart(user.getId());
        }
        //页面重定向，解决没刷新一次，就提交一次订单的问题！
        return "redirect:/order/payment/" + kuPinResult.getData() + ".html";
    }

    /**
     * 订单支付页面
     */
    @RequestMapping("/payment/{orderId}")
    public String orderInfo(@PathVariable String orderId, Model model) {
        //调用服务层查询订单
        KuPinResult kuPinResult = orderService.getOrderInfo(orderId);

        if (kuPinResult == null) {
            //找不到订单，返回404页面
            return "error/404";
        }

        if (kuPinResult.getStatus() == KuPinConstant.KuPinResult_status_success) {
            //redis中能取到订单信息，也即订单未取消，从kupinResult中取数据
            Map<String, Object> data = (Map<String, Object>) kuPinResult.getData();
            TbOrder orderInfo = (TbOrder) data.get("orderInfo");
            Long orderTtl = (Long) data.get("orderTtl");
            //将数据传递给页面
            model.addAttribute("payment", orderInfo.getPayment());
            model.addAttribute("orderTtl", orderTtl);

        } else {
            //数据库中查到订单信息
            TbOrder orderInfo = (TbOrder) kuPinResult.getData();
            String msg = kuPinResult.getMsg();
            //将数据传递给页面
            model.addAttribute("msg", msg);
        }
        model.addAttribute("orderId", orderId);
        //返回逻辑视图
        return "orderPayment";
    }
}
